package com.nt.train.beanlife;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
/**
 * 模拟bean实例化生命周期处理
 * https://www.cnblogs.com/hurro/p/13549295.html
 * BeanNameAware  set bean 实例化名称
 * @author hlf
 * @version 1.0
 * @date 2022/9/28 21:19
 */
public class MyBeanLifeService implements BeanNameAware ,BeanFactoryAware,InitializingBean,ApplicationContextAware {

    private String name;

    private BeanFactory beanFactory;

    public MyBeanLifeService() {
        System.out.println("MyBeanLifeService对象正在实例化 name="+ name);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println(">>>开始初始化 调用MyBeanLifeService setName()方法设置对象属性");
        this.name = name;
    }

    @Override
    public void setBeanName(String beanName) {
        System.out.println("MyBeanLifeService实例属性设置完成，调用setBeanName() beanName=" + beanName);
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println("调用 setBeanFactory() 设置beanFactory实例到A对象中");
        this.beanFactory = beanFactory;
        System.out.println("a >>>>>>>>"+ beanFactory.getBean("myBeanLifeService").toString());

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        /**同一级的生命周期方法中最后一个被调用的,但是只会调用一次，之后在调用bean的setxx()方法更改属性时将不会再被被调用到 */
        System.out.println("调用afterPropertiesSet() MyBeanLifeService 对象的属性设置已经完成了 name=" + name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("调用setApplicationContext  ApplicationContext的值为" + applicationContext.toString());
    }
}
